const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    info: [],
    recommand:[],
    comd:true, //底部继续加载
    attr_show: false,
    intro_show: false,
    attrList:[],
    introList:[],
    attrType:'',
    switchId:'0',
    totalNum:'0',
    totalMoney:'0',
    is_attrList:false,
    is_introList:false,
    coll:'',
    forbid:'1',
    collect_id:'',
    type:'',
    show: false,
    animate:false,
    scroll:true,
    canAdd:false,
    telBlockState: false,
    getCodeText: "获取验证码",
    tel: "",
    telCode: "",
    applyMsgState: true,
    getCodeState: false,
  },
  'choose-attr':function(){
    let that = this;
    // that.setData({ attr_show: true,scroll: false })
    if (that.data.is_attrList){
      that.setData({ attr_show: true,scroll: false })
      return;
    }
    wx.request({
      url: app.buildUrl('/shop/supplier-goods/get-goods-attr'),
      header: app.buildHeader(),
      method: 'GET',
      data: { goods_id: that.data.id },
      success: function (res) {
        if (res.data.code == 200) {
          let newList = res.data.data.data; 
          newList.forEach(function(i,index){
            i.num = 0;
            i.list.forEach(function(j){
              j.num = 0;
              j.inv = j.inventory;
            })
          })
          that.setData({
            attrList: newList,
            attrType: res.data.data.type,
            is_attrList: true,
            attr_show: true, scroll: false
          })
        }
      }
    })
  },
  'desc': function (e) {
    let idx = e.target.dataset.index;
    let num = this.data.attrList[this.data.switchId].list[idx].num;
    let newList = this.data.attrList;
    if(num<=0){
      return;
    }else{
      num--;
      newList[this.data.switchId].list[idx].num = num
      newList[this.data.switchId].list[idx].inventory++
      this.setData({
        attrList: newList
      })
      this.count();
    }
    this.jungle();
  },
  'inc': function (e){
    let idx = e.target.dataset.index;
    let inventory = e.target.dataset.inventory;
    let inv = e.target.dataset.inv;
    let num = this.data.attrList[this.data.switchId].list[idx].num;
    let newList = this.data.attrList;
    if ( inventory<=0 ){
      app.showToast('数量不能大于库存');
    }else{
      num++;
      newList[this.data.switchId].list[idx].num = num
      newList[this.data.switchId].list[idx].inventory--    
      this.setData({
        attrList: newList
      })
      this.count();
    }
    this.jungle();
  },
  'inputChange':function(e){
    let inputNum = parseInt(e.detail.value);
    if (e.detail.value == '') { inputNum = 0; }
    let idx = e.target.dataset.index;
    let inventory = e.target.dataset.inventory;
    let inv = e.target.dataset.inv;
    let num = this.data.attrList[this.data.switchId].list[idx].num;
    let newList = this.data.attrList;
    if (inputNum > inv){
      app.showToast("数量不能大于库存")
    }else{
      newList[this.data.switchId].list[idx].num = inputNum;
      newList[this.data.switchId].list[idx].inventory = inv - inputNum;
      this.setData({
        attrList: newList
      })
      this.count();
    }
    this.jungle();
  },
  'close-ch':function(){
    this.setData({ attr_show: false, scroll:true })
  },
  'switch':function(e){
    this.setData({ switchId : e.target.dataset.index })
  },
  'attr-intro':function(){
    let that = this;
    // that.setData({ intro_show: true, scroll: false })
    if (that.data.is_introList) {
      that.setData({ intro_show: true, scroll: false })
      return;
    }
    wx.request({
      url: app.buildUrl('/shop/supplier-goods/get-attr-deion'),
      header: app.buildHeader(),
      method: 'GET',
      data: {goods_id: that.data.id},
      success: function(res){
        if(res.data.code == 200){
          if(res.data.data.length>0){
            that.setData({
              introList: res.data.data,
              is_introList: true,
              intro_show: true, scroll: false
            })
          }else{
            app.showToast("暂无详细参数");
          }
        }
      }
    })
  },
  'close_intro':function(){
    this.setData({ intro_show: false, scroll:true })
  },
  'noinv':function(){
    app.showToast("库存为0，不能操作");
  },
  'count':function(){
    let that = this;
    let num = 0, money = 0;
    let newList = that.data.attrList;
    if(that.data.type != 5){
      newList.forEach(function (i) {
        i.num = 0;
        i.list.forEach(function (j) {
          num += j.num;
          money = money + j.num * j.original_price;
          i.num += j.num
        })
      })
    }else{
      newList.forEach(function (i) {
        i.num = 0;
        i.list.forEach(function (j) {
          num += j.num;
          money = money + j.num * j.discount_price;
          i.num += j.num
        })
      })
    }
    that.setData({
      totalNum: num,
      totalMoney: parseFloat(money).toFixed(2),
      attrList: newList
    })
  },
  'collection':function(e){
    let that = this;
    let id = e.currentTarget.dataset.id;
    wx.request({
      url: app.buildUrl('/shop/shop/add-collection'),
      header: app.buildHeader(),
      method: 'GET',
      data: { goods_id: id},
      success:function(res){
        if(res.data.code == 200){
          app.showToast(res.data.msg)
          that.setData({ coll: 1, collect_id: res.data.data.collection_id })
        }else{
          app.showToast(res.data.msg)
        }
      }
    })
  },
  'cancelCollection':function(e){
    let that = this;
    let id = e.currentTarget.dataset.collect;
    wx.request({
      url: app.buildUrl('/shop/shop/del-collection'),
      header: app.buildHeader(),
      method: 'GET',
      data: { id: id },
      success: function (res) {
        if (res.data.code == 200) {
          app.showToast('取消成功')
          that.setData({ coll: 0 })
        } else {
          app.showToast(res.data.msg)
        }
      }
    })
  },
  'jungle':function(){
    let that = this,
      newList = this.data.attrList,
      go=true;
    newList.forEach(function(i){
      i.list.forEach(function(j){
        if (go) {
          if(j.num!=0){
            that.setData({ canAdd: true });
            go=false;
          }else{
            that.setData({ canAdd: false });
          }

        }
        
      })
    })
  },
  'add-car':function(){
    let that = this,
      newList = this.data.attrList,
      lastList = [];
    newList.forEach(function(i){
      i.list.forEach(function(j){
        if(j.num!=0){
          let one = [];
          one.push(j.goods_id)
          one.push(j.id)
          one.push(j.num)
          lastList.push(one)
        }
      })
    })
    wx.request({
      url: app.buildUrl('/shop/shopping-cart/add-shopping-cart'),
      header: app.buildHeader(),
      method: 'POST',
      data: lastList,
      success: function (res) {
        if (res.data.code == 200) {
          app.showToast(res.data.msg);
          that.setData({ animate: true })
          setTimeout(function () {
            that.setData({
              is_attrList: false, attr_show: false, animate: false,
              scroll: true,
              totalNum: 0, //价格 数量置0
              totalMoney: 0,
            })
          }, 500)
        } else {
          app.showToast(res.data.msg)
        }
      }
    })
  },
  //授权
  onGotUserInfo(e) {
    let that = this;
    // console.log(e.detail)
    if (e.detail.userInfo) {
      that.setData({
        show: false,
        telBlockState: true
      });
      wx.request({
        url: app.buildUrl('/shop/shop/save-user-info'),
        header: app.buildHeader(),
        method: 'POST',
        data: {
          url: e.detail.userInfo.avatarUrl,
          nickname: e.detail.userInfo.nickName
        },
        success: res => {
          if (res.data.code == 200) {
            // 再次请求
            wx.setStorageSync('status', 200)
            // that.load();
          } else {
            app.showToast(res.data.msg)
          }
        }
      })
    }
  },
  telIpt(e) { //电话号码
    this.setData({
      tel: e.detail.value
    })
  },
  codeIpt(e) { //验证码
    this.setData({
      telCode: e.detail.value
    })
  },
  verification() { //验证手机
    let that = this;
    var tel = that.data.tel,
      telReg = /^1\d{10}$/;
    if (tel === "" || !tel) {
      app.showToast("电话号码不能为空！")
      return false;
    } else if (!telReg.test(tel)) {
      app.showToast("电话号码格式错误！")
      return false;
    } else {
      return true;
    }
  },
  telConfirm() { // 确认
    let that = this;
    if (that.verification()) {
      if (that.data.telCode == "" || !that.data.telCode) {
        app.showToast("请输入验证码！")
      } else {
        wx.request({
          url: app.buildUrl('/shop/shop/save-shop-info'),
          header: app.buildHeader(),
          method: 'POST',
          data: {
            phone: that.data.tel,
            code: that.data.telCode
          },
          success: function (res) {
            if (res.data.code == 200) {
              app.showToast(res.data.msg)
              that.setData({
                tel: "",
                telBlockState: false
              })
              // 再次请求
              wx.setStorageSync('status', 200)
              that.load();
            } else {
              app.showToast(res.data.msg)
            }
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    }
  },
  getCodeFun() { // 获取验证码
    var that = this;
    if (that.verification()) {
      let [times, state, timer] = [90, that.data.getCodeState, null];
      if (state) {
        return
      }
      wx.request({
        url: app.buildUrl('/shop/shop/send-code'),
        header: app.buildHeader(),
        method: 'POST',
        data: {
          phone: that.data.tel
        },
        success: function (res) {
          if (res.data.code == 200) {
            that.setData({
              getCodeState: true,
              getCodeText: times + "s"
            })
            timer = setInterval(function () {
              times--;
              that.setData({
                getCodeText: times + "s"
              })
              if (times == 0) {
                clearTimeout(timer)
                timer = null;
                times = 180;
                that.setData({
                  getCodeText: "获取验证码",
                  getCodeState: false
                })
              }
            }, 1000)
            app.showToast(res.data.msg)
          } else {
            app.showToast(res.data.msg)
          }
        },
        fail: function (res) {
          console.log(res)
        }
      })
    }
  },
  telClose() {
    this.setData({
      telBlockState: false,
      show: true
    })
    this.load()
  },
  apply() {
    this.setData({
      applyMsgState: false
    })
  },
  copyUrl(e) {
    wx.setClipboardData({
      data: e.target.dataset.url,
      success: function (res) {
        app.showToast('复制成功')
      }
    })

  },
  back() {
    this.setData({
      applyMsgState: true
    })
  },
  load(){
    let that = this;
    wx.request({
      url: app.buildUrl('/shop/supplier-goods/get-goods-info'),
      header: app.buildHeader(),
      method: 'GET',
      data: { goods_id: that.data.id },
      success: function (res) {
        if (res.data.code = 200) {
          let newList = res.data.data;
          newList.max_price = parseFloat(newList.max_price).toFixed(2);
          newList.min_price = parseFloat(newList.min_price).toFixed(2);
          newList.freight = parseFloat(newList.freight).toFixed(2);
          that.setData({ info: newList, collect_id: res.data.data.is_collect, type: res.data.data.goods_type })
          if (res.data.data.is_collect == 0) {
            that.setData({ coll: 0 })
          } else {
            that.setData({ coll: 1 })
          }
          if (res.data.data.is_del == 1 || res.data.data.status == 0) {
            that.setData({ forbid: 0 })
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let id = options.id ? options.id : options.scene ? decodeURIComponent(options.scene) : '1';
    that.setData({
      id: id
    })
    app.getUserInfoFirst().then(function (res) {
      if (res.status == 200) {
        if (wx.getStorageSync("status") != 200) {
          that.setData({ show: true })
        } else if (wx.getStorageSync("status") == 200) {
          that.setData({ show: false })
          that.load();
        }
      }
    })
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if (that.data.comd){
      wx.request({
        url: app.buildUrl('/shop/supplier-goods/get-goods-list'),
        header: app.buildHeader(),
        method: 'GET',
        data: {
          goods_id: that.data.id || 31,
          goods_type: that.data.info.goods_type
        },
        success: function (res) {
          if (res.data.code = 200) {
            let newList = res.data.data;
            newList.forEach(function (i) {
              i.max_discount_price = parseFloat(i.max_discount_price).toFixed(2);
              i.max_original_price = parseFloat(i.max_original_price).toFixed(2);
              i.min_discount_price = parseFloat(i.min_discount_price).toFixed(2);
              i.min_original_price = parseFloat(i.min_original_price).toFixed(2);
              if (parseInt(i.display_sales) > 10000) {
                i.display_sales = i.display_sales / 10000 + 'w'
              }
            })
            that.setData({ recommand: newList, comd:false })
          }
        }
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})